package H02.h1;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@WebServlet("/s02")
@MultipartConfig//此注释支持文件上传
public class Servlet02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String StudentId=req.getParameter("StudentId");
        String StudentName=req.getParameter("StudentName");
        Part avatarPart=req.getPart("avatar");
        //获取文件的扩展名
        String fileName=avatarPart.getSubmittedFileName();
        String fileExtension="";
        if (fileName !=null&&fileName.lastIndexOf('.')!=-1){
            fileExtension=fileName.substring(fileName.lastIndexOf('.'));
        }
        //创建存储目录
        String directoryName=StudentId+"-"+StudentName;
        String uploadPath="D:\\java大作业\\javaweb第二次实验报告\\upload" +
                File.separator + directoryName;
        File uploadDir=new File(uploadPath);
        //如果目录不存在则创建
        if(!uploadDir.exists()){
            uploadDir.mkdirs();//mkdirs()方法可以递归创建多级目录
        }
        //定义文件的目标路径
        String avatarFilePath=uploadPath+File.separator+"avatar"+fileExtension;

        //将文件写入目标路径
        try(InputStream inputStream=avatarPart.getInputStream()){
            java.nio.file.Files.copy(inputStream,new File(avatarFilePath).toPath());
        }

        //反馈结果
        resp.getWriter().println("头像上传成功！储存在："+avatarFilePath);
        }
    }

